<template>
  <view class="practice-page">
    <Navbar title="金仕咨询" background="#fff">
      <!-- 顶部状态栏 -->
      <view class="status-bar">
        <view class="status-left">
          <u-icon name="close" size="28" color="#333" @click="exitPractice"></u-icon>
          <view class="time-info">
            <image src="/static/info/time.png" class="time-icon" mode="aspectFit"></image>
            <text class="time-text">{{ formatTime(remainingTime) }}</text>
          </view>
        </view>
      </view>
    </Navbar>
    <!-- 练习信息栏 -->
    <view class="practice-info">
      <text class="practice-title">{{ practiceInfo.title }}</text>
      <view class="practice-actions">
        <image src="/static/qs/qs-list.png" class="action-icon" mode="aspectFit" @click="showAnswerCard"></image>
      </view>
    </view>

    <!-- 题目卡片 -->
    <view class="question-card">
      <!-- 题目类型和进度 -->
      <view class="question-header">
        <view class="question-type">
          <text class="type-text">{{ currentQuestion.type }}</text>
        </view>
        <text class="question-progress"><text style="font-size: 32rpx;color: #333;font-weight: 500">{{ currentIndex + 1 }}</text>/{{ totalQuestions }}</text>
      </view>

      <!-- 题目内容 -->
      <view class="question-content">
        <text class="question-title">{{ currentQuestion.title }}</text>

        <!-- 题目图片 -->
        <view class="question-images" v-if="currentQuestion.image">
          <view
            class="image-item"
            v-for="(imgSrc, index) in getImageList(currentQuestion.image)"
            :key="index"
            @click="previewImage(currentQuestion.image, index)"
          >
            <image :src="imgSrc" class="image-content" mode="aspectFill"></image>
          </view>
        </view>
      </view>

      <!-- 选项列表 -->
      <view class="options-list">
        <view
          class="option-item"
          v-for="(option, index) in currentQuestion.options"
          :key="index"
          :class="{
            'selected': selectedAnswer === option.key,
            'correct': showAnswer && option.is_correct,
            'wrong': showAnswer && selectedAnswer === option.key && !option.is_correct
          }"
          @click="selectOption(option.key)"
        >
          <view class="option-circle">
            <text class="option-key">{{ option.key }}</text>
          </view>
          <text class="option-text">{{ option.text }}</text>
          <!-- 正确答案标识 -->
          <view class="answer-indicator" v-if="showAnswer && option.is_correct">
            <text class="correct-icon">✓</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部操作栏 -->
    <view class="bottom-actions">
      <button class="prev-btn" v-if="currentIndex > 0" @click="prevQuestion">
        <text class="btn-text">上一题</text>
      </button>
      <button class="next-btn" v-if="currentIndex < totalQuestions - 1" @click="nextQuestion">
        <text class="btn-text">下一题</text>
      </button>
    </view>

    <!-- 答题卡弹窗 -->
    <u-popup v-model="showAnswerCardPopup" mode="bottom" border-radius="32rpx 32rpx 0 0" height="60%">
      <view class="answer-card-popup">
        <view class="popup-header">
          <view class="popup-title-section">
            <text class="popup-title">答题卡</text>
            <text class="popup-subtitle" v-if="getUnansweredCount() > 0">
              还有 {{ getUnansweredCount() }} 题未答
            </text>
          </view>
          <text class="popup-close" @click="closeAnswerCard">×</text>
        </view>

        <view class="popup-content">
          <view class="answer-grid">
            <view
              class="answer-item"
              v-for="(answer, index) in answerRecord"
              :key="index"
              :class="{
                'answered': answer.answered,
                'current': index === currentIndex
              }"
              @click="jumpToQuestion(index)"
            >
              <text class="answer-number">{{ index + 1 }}</text>
            </view>
          </view>
        </view>

        <view class="popup-footer">
          <button class="submit-btn" @click="submitPractice">提交答案</button>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import Navbar from "../../components/Navbar.vue";
import dayjs from "dayjs";

export default {
  components: {Navbar},
  data() {
    return {
      // 练习信息
      practiceInfo: {
        id: null,
        title: '专项练习(政治理论)',
        category: 'political_theory'
      },
      answerRecordId: 0,
      // 题目列表
      questions: [],
      // 当前题目索引
      currentIndex: 0,
      // 答题记录
      answerRecord: [],
      // 当前选择的答案
      selectedAnswer: '',
      // 剩余时间（秒）
      remainingTime: 1800, // 30分钟
      // 是否显示答案
      showAnswer: false,
      // 是否显示答题卡
      showAnswerCardPopup: false,
      // 定时器
      timer: null
    }
  },
  computed: {
    // 当前题目
    currentQuestion() {
      return this.questions[this.currentIndex] || {};
    },
    // 总题目数
    totalQuestions() {
      return this.questions.length;
    }
  },
  onLoad(options) {
    if (!options.id) {
      // 返回
      uni.navigateBack();
      return
    }
    this.initPractice(options.id);
  },
  onUnload() {
    // 清除定时器
    if (this.timer) {
      clearInterval(this.timer);
    }
  },
  methods: {
    // 初始化练习
    async initPractice(id) {
      try {
        // 创建答题记录
        const result = await this.$api.createPracticeRecord({
          bank_id: id,
          user_id: this.userInfo.id
        });
        this.practiceInfo = result.questionBank;
        this.questions = JSON.parse(result.questions.questions);
        // 过期时间-开始时间等于剩余秒 dayjs(时间A).diff(时间B, '单位')
        this.remainingTime = dayjs(result.questions.expire_time).diff(dayjs(), 'seconds')
        this.answerRecordId = result.questions.id
        console.log('questions', this.questions)
        // 初始化答题记录
        this.answerRecord = this.questions.map(() => ({
          id: this.questions.id,
          answered: false,
          selected_answer: '',
          is_correct: false
        }));

        // 开始计时
        this.startTimer();

      } catch (error) {
        console.error('初始化练习失败:', error);
      }
    },

    // 开始计时
    startTimer() {
      this.timer = setInterval(() => {
        if (this.remainingTime > 0) {
          this.remainingTime--;
        } else {
          this.submitPractice();
        }
      }, 1000);
    },

    // 格式化时间
    formatTime(seconds) {
      const minutes = Math.floor(seconds / 60);
      const remainingSeconds = seconds % 60;
      return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
    },

    // 选择选项
    selectOption(optionKey) {
      if (this.showAnswer) return; // 显示答案时不允许选择

      this.selectedAnswer = optionKey;

      // 更新答题记录
      this.answerRecord[this.currentIndex] = {
        answered: true,
        selected_answer: optionKey,
        is_correct: this.currentQuestion.options.find(opt => opt.key === optionKey)?.is_correct || false,
        ...this.currentQuestion
      };

      // 如果是最后一题，自动弹出答题卡
      if (this.currentIndex === this.totalQuestions - 1) {
        setTimeout(() => {
          this.showAnswerCard();
        }, 500); // 延迟500ms，让用户看到选择效果
      }
    },

    // 上一题
    prevQuestion() {
      if (this.currentIndex > 0) {
        this.currentIndex--;
        this.selectedAnswer = this.answerRecord[this.currentIndex].selected_answer || '';
      }
    },

    // 下一题
    nextQuestion() {
      if (this.currentIndex < this.totalQuestions - 1) {
        this.currentIndex++;
        this.selectedAnswer = this.answerRecord[this.currentIndex].selected_answer || '';
      }
    },

    // 跳转到指定题目
    jumpToQuestion(index) {
      this.currentIndex = index;
      this.selectedAnswer = this.answerRecord[index].selected_answer || '';
      this.closeAnswerCard();
    },

    // 显示答题卡
    showAnswerCard() {
      this.showAnswerCardPopup = true;
    },

    // 关闭答题卡
    closeAnswerCard() {
      this.showAnswerCardPopup = false;
    },

    // 切换答案模式
    toggleAnswerMode() {
      this.showAnswer = !this.showAnswer;
    },

    // 切换收藏
    toggleFavorite() {
      // 收藏功能实现
      uni.showToast({
        title: '收藏功能开发中',
        icon: 'none'
      });
    },

    // 显示更多选项
    showMoreOptions() {
      uni.showActionSheet({
        itemList: ['暂停练习', '重新开始', '查看解析'],
        success: (res) => {
          switch (res.tapIndex) {
            case 0:
              this.pausePractice();
              break;
            case 1:
              this.restartPractice();
              break;
            case 2:
              this.showAnalysis();
              break;
          }
        }
      });
    },

    // 暂停练习
    pausePractice() {
      if (this.timer) {
        clearInterval(this.timer);
      }
      uni.showModal({
        title: '练习已暂停',
        content: '是否继续练习？',
        success: (res) => {
          if (res.confirm) {
            this.startTimer();
          } else {
            this.exitPractice();
          }
        }
      });
    },

    // 重新开始
    restartPractice() {
      uni.showModal({
        title: '确认重新开始',
        content: '当前进度将丢失，是否继续？',
        success: (res) => {
          if (res.confirm) {
            this.initPractice();
          }
        }
      });
    },

    // 显示解析
    showAnalysis() {
      this.showAnswer = true;
    },

    // 提交练习
    async submitPractice() {
      // 检查是否有未答题目
      const unansweredCount = this.answerRecord.filter(answer => !answer.answered).length;

      if (unansweredCount > 0) {
        // 有未答题目，进行二次确认
        uni.showModal({
          title: '确认提交',
          content: `还有 ${unansweredCount} 道题目未作答，确定要提交吗？`,
          confirmText: '确定提交',
          cancelText: '继续答题',
          success: (res) => {
            if (res.confirm) {
              this.doSubmitPractice();
            } else {
              // 用户选择继续答题，关闭答题卡
              this.closeAnswerCard();
            }
          }
        });
      } else {
        // 全部答完，直接提交
        this.doSubmitPractice();
      }
    },

    // 执行提交练习
    async doSubmitPractice() {
      try {
        // 停止计时
        if (this.timer) {
          clearInterval(this.timer);
        }

        // 显示加载提示
        uni.showLoading({
          title: '提交中...'
        });

        // 提交答案
        const result = await this.$api.submitPracticeRecord({
          id: this.answerRecordId,
          answers: this.answerRecord
        });

        // 隐藏加载提示
        uni.hideLoading();

        // 跳转到结果页面
        uni.redirectTo({
          url: `/pages/question/result?practiceId=${result.id}`
        });

      } catch (error) {
        // 隐藏加载提示
        uni.hideLoading();

        console.error('提交练习失败:', error);
        uni.showToast({
          title: '提交失败',
          icon: 'none'
        });
      }
    },

    // 获取未答题目数量
    getUnansweredCount() {
      return this.answerRecord.filter(answer => !answer.answered).length;
    },

    // 获取图片列表
    getImageList(imageStr) {
      if (!imageStr) return [];
      return imageStr.split(',').filter(img => img.trim());
    },

    // 预览图片
    previewImage(imageStr, currentIndex) {
      const imageList = this.getImageList(imageStr);
      if (imageList.length === 0) return;

      uni.previewImage({
        current: currentIndex,
        urls: imageList,
        indicator: 'number',
        loop: true
      });
    },

    // 退出练习
    exitPractice() {
      uni.showModal({
        title: '确认退出',
        content: '退出即提交答题？',
        success: (res) => {
          if (res.confirm) {
            // 停止计时
            if (this.timer) {
              clearInterval(this.timer);
            }

            // 显示加载提示
            uni.showLoading({
              title: '提交中...'
            });

            // 提交答案
            this.$api.submitPracticeRecord({
              id: this.answerRecordId,
              answers: this.answerRecord
            }).then(res => {
              // 隐藏加载提示
              uni.hideLoading();
              uni.showToast({
                title: '提交成功',
                icon: 'success'
              })
              setTimeout(() => {
                uni.navigateBack();
              },1000)
            })

          }
        }
      });
    }
  }
}
</script>

<style lang="scss">
.practice-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;

  // 顶部状态栏
  .status-bar {
    background: #FFFFFF;
    padding: 32rpx 0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1rpx solid #f0f0f0;

    .status-left {
      display: flex;
      align-items: center;

      .close-btn {
        font-size: 48rpx;
        color: #999999;
        margin-right: 32rpx;
        line-height: 1;
        display: flex;
        align-items: center;
      }

      .time-info {
        display: flex;
        align-items: center;
        margin-left: 24rpx;

        .time-icon {
          width: 32rpx;
          height: 32rpx;
          margin-right: 8rpx;
        }

        .time-text {
          font-size: 28rpx;
          color: #333333;
          font-weight: bold;
        }
      }
    }

    .status-right {
      display: flex;
      align-items: center;

      .more-icon,
      .eye-icon {
        width: 48rpx;
        height: 48rpx;
        margin-left: 24rpx;
      }
    }
  }

  // 练习信息栏
  .practice-info {
    background: #f8f8f8;
    padding: 24rpx 32rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .practice-title {
      font-size: 28rpx;
      color: #333333;
      font-weight: bold;
    }

    .practice-actions {
      display: flex;
      align-items: center;

      .action-icon {
        width: 40rpx;
        height: 40rpx;
        margin-left: 24rpx;
      }
    }
  }

  // 题目卡片
  .question-card {
    flex: 1;
    background: #FFFFFF;
    margin: 24rpx;
    margin-bottom: 160rpx; // 为固定底部按钮留出空间
    border-radius: 16rpx;
    padding: 32rpx;

    .question-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 32rpx;

      .question-type {
        color:#539DF3;
        background: rgba(83, 157, 243, 0.2);
        padding: 8rpx 16rpx;
        border-radius: 20rpx;

        .type-text {
          font-size: 24rpx;
        }
      }

      .question-progress {
        font-size: 26rpx;
        color: #666666;
      }
    }

    .question-content {
      margin-bottom: 48rpx;

      .question-title {
        font-size: 32rpx;
        color: #333333;
        line-height: 1.6;
        margin-bottom: 24rpx;
        display: block;
      }

      .question-images {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        gap: 16rpx;
        margin: 24rpx 0;

        .image-item {
          aspect-ratio: 1;
          border-radius: 8rpx;
          overflow: hidden;
          background: #f5f5f5;

          .image-content {
            width: 100%;
            height: 100%;
            border-radius: 8rpx;
          }
        }
      }
    }

    .options-list {
      .option-item {
        display: flex;
        align-items: center;
        padding:12rpx 24rpx;
        margin-bottom: 16rpx;
        // background: #f8f8f8;
        border-radius: 12rpx;
        // border: 2rpx solid transparent;
        position: relative;

        &.selected {
          background: #e6f3ff;
          border-color: #539DF3;
        }

        &.correct {
          background: #f6ffed;
          border-color: #52c41a;
        }

        &.wrong {
          background: #fff2f0;
          border-color: #ff4d4f;
        }

        .option-circle {
          width: 60rpx;
          height: 60rpx;
          border-radius: 50%;
          background: #FFFFFF;
          border: 2rpx solid #e0e0e0;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 24rpx;
          flex-shrink: 0;

          .option-key {
            font-size: 28rpx;
            color: #333;
          }
        }

        .option-text {
          flex: 1;
          font-size: 28rpx;
          color: #333333;
          line-height: 1.4;
        }

        .answer-indicator {
          position: absolute;
          right: 24rpx;

          .correct-icon {
            font-size: 32rpx;
            color: #52c41a;
            font-weight: bold;
          }
        }
      }
    }
  }

  // 底部操作栏
  .bottom-actions {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background: #FFFFFF;
    padding: 24rpx;
    display: flex;
    gap: 24rpx;
    border-top: 1rpx solid #f0f0f0;
    z-index: 100;

    .prev-btn,
    .next-btn {
      flex: 1;
      height: 88rpx;
      border-radius: 16rpx;
      border: none;
      display: flex;
      align-items: center;
      justify-content: center;

      .btn-text {
        font-size: 32rpx;
        color: #FFFFFF;
        font-weight: bold;
      }
    }

    .prev-btn {
      background: #33B6D4;
    }

    .next-btn {
      background: #539DF3;
    }
  }

  // 答题卡弹窗
  .answer-card-popup {
    height: 100%;
    display: flex;
    flex-direction: column;

    .popup-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 32rpx;
      border-bottom: 1rpx solid #f0f0f0;

      .popup-title-section {
        display: flex;
        flex-direction: column;
        gap: 8rpx;

        .popup-title {
          font-size: 32rpx;
          font-weight: bold;
          color: #333333;
        }

        .popup-subtitle {
          font-size: 24rpx;
          color: #ff4d4f;
        }
      }

      .popup-close {
        font-size: 48rpx;
        color: #999999;
        line-height: 1;
        padding: 8rpx;
      }
    }

    .popup-content {
      flex: 1;
      padding: 32rpx;
      overflow-y: auto;

      .answer-grid {
        display: grid;
        grid-template-columns: repeat(5, 1fr);
        gap: 32px;

        .answer-item {
          aspect-ratio: 1;
          background: #f5f5f5;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          border: 2rpx solid transparent;

          &.answered {
            background: #539DF3;
            border-color: #539DF3;

            .answer-number {
              color: #FFFFFF;
            }
          }

          &.current {
            border-color: #539DF3;
            background:rgb(234, 238, 243)
          }

          .answer-number {
            font-size: 28rpx;
            color: #333333;
            font-weight: bold;
          }
        }
      }
    }

    .popup-footer {
      padding: 32rpx;
      border-top: 1rpx solid #f0f0f0;

      .submit-btn {
        width: 100%;
        height: 88rpx;
        background: #539DF3;
        border-radius: 16rpx;
        border: none;
        display: flex;
        align-items: center;
        justify-content: center;
          color: #FFFFFF;
        .btn-text {
          font-size: 32rpx;
          color: #FFFFFF;
          font-weight: bold;
        }
      }
    }
  }
}
</style>
